# -*- coding:utf-8 -*-
# 黑cyc宇
from flask import Blueprint, request, current_app, jsonify
from bot.plugins._on_env import *
import re, json

route_parse_handler = Blueprint('route_parse_handler', __name__)

@route_parse_handler.route('/parse')
def parse():
    info = request.args
    event = info['event']

    if event in ['friend_msg', 'group_msg']:
        solve(info, 'command')
    elif event in ['group_member_add', 'group_member_decrease', 'friend_verify']:
        solve(info, 'request')
    elif event in ['received_transfer', 'scan_cash_money', 'contacts_change', 'sys_msg']:
        solve(info, 'notice')
    elif event in ['init', 'enable', 'login', 'stop']:
        eval(f'{event}')(current_app, info)
    elif event == 'get_msg':
        try:
            uuid = int(info['uuid'])
            ret = current_app.ret_msg_dict[uuid]
            try: del current_app.ret_msg_dict[uuid]
            except: pass
            ret = json.dumps({'data': ret, 'code': 200}).replace("\\n","<%n%>")
            return ret
        except: pass
    return ''

def solve(info, event):
    cmd, args = get_cmd_arg(current_app, info['msg'])
    for cmds, func in current_app.cmd_route[event]:
        if cmd in cmds:
            func(info, args)

def get_cmd_arg(bot, msg):
    # ret = msg.split(bot.config['SEP'])
    ret = re.split(f"{bot.config['SEP']}+", msg.strip())
    cmd = ret[0]
    args = ret[1:] if len(ret) > 1 else []
    return cmd, args